package com.beiding.dbrequest.common;

import io.netty.channel.ChannelHandlerContext;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 通道选择时的元数据
 *
 * @author 丁常磊
 * @date 2021/9/22 9:47
 */

class ChannelHolderForCallback {

    @Setter
    @Getter
    private ChannelHandlerContext channelHandlerContext;

    /**
     * 是否已经激活
     */
    private boolean active;

    /**
     * 是否未激活
     */
    private boolean inactive;

    private Set<ChannelCallback> activeCallbacks;

    private Set<ChannelCallback> inactiveCallbacks;


    synchronized void addActive(ChannelCallback callback) {
        if (activeCallbacks == null) {
            activeCallbacks = new HashSet<>();
        }
        activeCallbacks.add(callback);
        if (active) {
            try {
                callback.callback(channelHandlerContext);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    synchronized void addInactive(ChannelCallback callback) {
        if (inactiveCallbacks == null) {
            inactiveCallbacks = new HashSet<>();
        }
        inactiveCallbacks.add(callback);

        if (inactive) {
            try {
                callback.callback(channelHandlerContext);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    synchronized void removeActive(ChannelCallback callback) {
        activeCallbacks.remove(callback);
    }
    synchronized void removeInactive(ChannelCallback callback) {
        inactiveCallbacks.remove(callback);
    }

    /**
     * 已经激活
     */
    synchronized void active() {
        active=true;
        //执行
        if (activeCallbacks != null) {
            for (ChannelCallback callback : activeCallbacks) {
                try {
                    callback.callback(channelHandlerContext);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    synchronized void inactive() {
        inactive=true;
        if (inactiveCallbacks != null) {
            for (ChannelCallback callback : inactiveCallbacks) {
                try {
                    callback.callback(channelHandlerContext);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
